import { Button, Col, Divider, List, Modal, Radio, Row, Steps, Empty,Tabs } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import { selectOkrList, queryDepMaster, querySubDeptAndPer, queryComment } from '@/services/okr'
import { TableOkr, TimeHeader, TreeSelectItem, CommentPart, OtherDept } from './components/index';
import styles from './index.less';
import { statusList } from './params';

const { Step } = Steps;
const { TabPane } = Tabs;

const IndexPage = () => {
  let mode_local = localStorage.getItem('okr_category');
  const [mode, setMode] = useState('0');
  const [showList, setShowList] = useState([]);
  const [createOkrVisible, setCreateOkrVisible] = useState(false);
  const [master, setMaster] = useState('ling sang');
  const [okrId, setOkrId] = useState(0);
  const [jurisdiction, setJurisdiction] = useState('1');
  const [category, setCategory] = useState('0');
  const [departmentId, setDepartmentId] = useState('');
  const [okrCategory, setOkrCategory] = useState(mode == '0' ? '2' : '1');
  const [okrDepartmentId, setOkrDepartmentId] = useState(); // 创建多个部门 选择其中一个
  const [okrDepartmentList, setOkrDepartmentList] = useState([]);
  const [okrEditCount, setOkrEditCount] = useState(0);
  const [departmentname, setDepartmentname] = useState('');
  const [current, setCurrent] = useState(0);
  const [departmentList, setDepartmentList] = useState([]);
  const [myList, setMyList] = useState([]);
  const [lowDepartList, setLowDepartList] = useState([])
  const [lowPersonList, setLowPersonList] = useState([])
  const [topPersonList, setTopPersonList] = useState([])
  const [topDepartList, setTopDepartList] = useState([])
  const [currSelectId, setCurrSelectId] = useState('0')
  const [commemt, setComment] = useState([])
  const [activeKey, setActiveKey] = useState('1')

  const getTimeRef = useRef();

  useEffect(() => {
    if(activeKey == '1'){
      initData();
      initLowLevel()
    }
  }, []);
  // useEffect(()=>{
  //   // 部门或者个人切换时，需要重新获取周期
   
    
  // }, [departmentId])
  const initData = async () => {
    const { year, quarter } = getTimeRef.current;
    if(year && quarter) {
      getData(year, quarter)
    }
  };
  const initLowLevel = async () => {
    const res = await querySubDeptAndPer();
    if(res.code == 200) {
      setLowDepartList(res.data.dept?.subDeptList || [])
      setLowPersonList(res.data.subPersonList || [])
      setDepartmentList(res.data.dept?.subDeptList || [])
      setDepartmentname(res.data.dept?.name);
      setTopDepartList(res.data.dept)
      setTopPersonList({name: '我的OKR', id: ''})
      setMyList(res.data.dept ? [res.data.dept] : [])
    }
  }

  const getData = async (year, quarter, currMode, currDepartment) => {
    const params = {
      type: currMode ? currMode : (mode === '0' ? '2' : '1'),
      year,
      quarter,
      departmentId: currDepartment,
    };
    const res = await selectOkrList(params);
    const newRes = res?.data?.okr?.objectiveList.length > 0 ? res.data.okr.objectiveList.map((item, index) => { return {...item, key: index} }) : []
    setShowList(newRes);
    setMaster(res.data?.okr?.username)
    setCategory(res.data?.okr?.type)
    setOkrId(res.data?.okr?.id)
    setCurrent(res?.data?.okr?.status??'0')
    if(res.data?.okr?.id){
      updateCommentList(res.data?.okr?.id)
    }
  };

  const updateCommentList = async (id) => {
    const commentList =  await queryComment({okrId: id})
    setComment(commentList.data.totalList || [])
  }

  const goNewOkrPage = async () => {
    // 发送权限接口
    const res = await queryDepMaster();
    if(res.code == 200){
      if(res.data.isLeader === 1) {
        setCreateOkrVisible(true)
        const departmentList = res.data.departmentList || []
        setOkrDepartmentList(departmentList)
        if(departmentList.length > 0) {
          setOkrDepartmentId(departmentList[0].id);
        }
      } else {
          message.warning('当前登录用户权限仅能创建个人OKR')
          history.push({
          pathname: '/newokr',
          query: {
            departmentId: '',
            category: '1', // 个人1，部门2
          },
        });
      }
    }
  };

  const updateList = (year, quarter, currmode, currDepartment,tip) => {
    if (year && quarter) {
      getData(year, quarter, mode ? currmode : mode == '0' ? '2' : '1', tip == '1' ? currDepartment: departmentId);
    }
  };
  const updateNewList = () => {
    setShowList([]);
  }
  const goOkrDetail = (id) => {
    history.push({
          pathname: '/newokr',
          query: {
              id,
              departmentId,
              category: mode == '0' ? '2' : '1',
          }
        })
  };
  const handleOk = () => {
    history.push({
      pathname: '/newokr',
      query: {
        category: okrCategory, // 创建个人还是部门
        departmentId:
          okrCategory === '2'
            ? okrDepartmentList.length > 0
              ? okrDepartmentId
              : ''
            : '',
      },
    });
  };
  const onchangeCurrent = (val) => {
    setCurrent(val);
  };
  const changeMode = (e) => {
    setMode(e.target.value);
    setCurrSelectId('-1')
    localStorage.removeItem('okr_category');
    if(e.target.value == '0'){
      setMyList([topDepartList])
      setDepartmentList(lowDepartList)
    }else {
      setMyList([topPersonList])
      setDepartmentList(lowPersonList)
    }
    setDepartmentId('')
    changeIdGetQuater(e.target.value, '')
  }
  const selectItem = (item) => {
    const id = item.id;
    setDepartmentId(id);
    setCurrSelectId(id)
    changeIdGetQuater('', id)
  }
  const updatedepartmentId = (val) => {
    setDepartmentId(val)
    setCurrSelectId(val)
    changeIdGetQuater('', val)
  }

  //  切换id时，重新获取周期
  const changeIdGetQuater = (currMode, id) => {
    const { year, quarter } = getTimeRef.current;
    getTimeRef.current.getQuarterFun(year, currMode || mode, id || '');
  }
  const onChangeTab = (key) => {
    setActiveKey(key)
  }
  const renderTab1 = () => {
    return <>
     <div className={styles.all_okr_wrap}>
            <div className={styles.okr_right_wrap}>
              <Row style={{ marginBottom: '15px' }} gutter={20}>
                <Col span={8}>
                  <TimeHeader
                    updateList={updateList}
                    updateNewList={updateNewList}
                    ref={getTimeRef}
                    mode={mode}
                    okrEditCount={okrEditCount}
                    departmentId={departmentId}
                  ></TimeHeader>
                </Col>
                <Col span={5} offset={9}>
                  {/* {mode == '0' &&<TreeSelectItem updatedepartmentId={updatedepartmentId} />} */}
                </Col>
                <Col span={2}>
                  <Button
                    style={{ float: 'right' }}
                    type="primary"
                    onClick={goNewOkrPage}
                  >
                    创建OKR
                  </Button>
                </Col>
              </Row>
              <div
                style={{ background: '#fff', padding: '10px' }}
                className={styles.okr_right_body}
              >
                <Radio.Group
                  onChange={changeMode}
                  value={mode}
                  style={{ marginBottom: 8 }}
                >
                  <Radio.Button value="0">部门OKR</Radio.Button>
                  <Radio.Button value="1">个人OKR</Radio.Button>
                </Radio.Group>
                {/* <div
                  style={{
                    width: '100%',
                    height: '20px',
                    background: '#d2e6f8',
                    margin: '8px 0',
                  }}
                ></div> */}
                <Row style={{background: '#edeef0', display: 'flex', justifyContent: 'space-between',padding: '20px'}}>
                  <Col span={2} className={styles.list_wrap} style={{background: '#fff'}}>
                    {myList.length > 0 && <List
                      header={<div>{mode == '0' ? '当前部门' : '个人OKR'}</div>}
                      // bordered
                      dataSource={myList}
                      renderItem={(item) => <List.Item onClick={() => selectItem(item)}><div style={item.id == currSelectId ? {color: '#54acfe', width: '100%', textShadow: '#fea153 1px 1px'} : {width: '100%'}}>{item.name}</div></List.Item>}
                    />}
                    {departmentList.length > 0 && <List
                      header={<div>{mode == '0' ? '下级部门' : '我的下属'}</div>}
                      // bordered
                      dataSource={departmentList}
                      renderItem={(item) => <List.Item onClick={() => selectItem(item)}><div style={item.id == currSelectId ? {color: '#54acfe', width: '100%', textShadow: '#fea153 1px 1px'} : {width: '100%'}}>{item.name}</div></List.Item>}
                    />}
                  </Col>
                  <Col span={17} style={{padding: '10px', background: '#fff'}}>
                    {showList.length > 0 && <div className={styles.stepWrap}>
                      <Steps
                        type="navigation"
                        current={current}
                        onChange={onchangeCurrent}
                        className="site-navigation-steps"
                      >
                        {statusList.map((item, index) => (
                          <Step
                            status={`${
                              Number(current) > index
                                ? 'wait'
                                : Number(current) == index
                                ? 'process'
                                : 'finish'
                            }`}
                            key={index}
                            title={item.title}
                          />
                        ))}
                      </Steps>
                    </div>}
                    {showList.length > 0 ? <TableOkr
                      goOkrDetail={goOkrDetail}
                      okrId={okrId}
                      jurisdiction={jurisdiction}
                      list={showList}
                      master={master}
                      category={category}
                    /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description='当前角色此周期下无OKR，快去创建吧！'/>}
                  </Col>
                  <Col span={4} style={{background: '#fff'}}>
                    <CommentPart okrId={okrId} commemt={commemt} updateCommentList={updateCommentList}/>
                  </Col>
                </Row>
              </div>
              {createOkrVisible && (
                <Modal
                  title="请选择创建OKR类型"
                  visible={createOkrVisible}
                  onOk={handleOk}
                  onCancel={() => {
                    setCreateOkrVisible(false);
                  }}
                >
                  <Radio.Group
                    onChange={(e) => {
                      setOkrCategory(e.target.value);
                    }}
                    value={okrCategory}
                  >
                    <Radio value="2">部门OKR</Radio>
                    <Radio value="1">个人OKR</Radio>
                  </Radio.Group>
                  {okrCategory === '2' && okrDepartmentList.length > 0 && (
                    <>
                      <Divider />
                      <Radio.Group
                        onChange={(e) => {
                          setOkrDepartmentId(e.target.value);
                        }}
                        value={okrDepartmentId}
                      >
                        {okrDepartmentList.map((item, index) => (
                          <Radio key={index} value={item.id}>{item.name}</Radio>
                        ))}
                      </Radio.Group>
                    </>
                  )}
                  {/* {okrCategory === '1' && (
                    <>
                      <Divider />
                      <Radio.Group value={departmentname}>
                        <Radio value={departmentname}>{departmentname}</Radio>
                      </Radio.Group>
                    </>
                  )} */}
                </Modal>
              )}
            </div>
          </div>
    </>
  }
  const renderTab2 = () => {
    return <>
        <OtherDept updatedepartmentId={updatedepartmentId}></OtherDept>
    </>
  }
  const items = [
    {
      key: '1',
      label: '当前部门',
      children: renderTab1(),
    },
    {
      key: '2',
      label: '其他部门',
      children: renderTab2(),
    },
  ];
  return (
    <div style={{width: '100%'}}>
    <Tabs
        onChange={onChangeTab}
        activeKey={activeKey}
        items={items}
        type="card"
      >
      </Tabs>
      </div>
  );
};

export default IndexPage;
